package com.wmh.baseservice.skd.controller;

import com.wmh.baseservice.common.service.TokenService;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.merchant.pojo.MerchantGroupGoods;
import com.wmh.baseservice.merchant.pojo.MerchantInfo;
import com.wmh.baseservice.merchant.service.MerchantGroupGoodsService;
import com.wmh.baseservice.merchant.service.MerchantInfoService;
import com.wmh.baseservice.skd.pojo.SkdGoodsSpec;
import com.wmh.baseservice.skd.service.SkdGoodsSpecService;
import com.wmh.baseservice.skd.service.SkdLeaderInfoService;
import com.wmh.baseservice.skd.service.SkdMemberInfoService;
import com.wmh.baseservice.user.enums.GroupGoodsOrderStatusEnum;
import com.wmh.baseservice.user.pojo.UsGroupGoodsOrder;
import com.wmh.baseservice.user.pojo.vo.UsGroupGoodsOrderRespVO;
import com.wmh.baseservice.user.service.UsGroupGoodsOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "团购商品订单相关接口")
@Validated
@RestController
@RequestMapping(value = "group-buy-orders", produces = "text/plain;charset=utf-8")
@Slf4j
public class GroupBuyOrderController {
    @Resource
    private TokenService tokenService;
    @Resource
    private UsGroupGoodsOrderService usGroupGoodsOrderService;
    @Resource
    private MerchantInfoService merchantInfoService;
    @Resource
    private MerchantGroupGoodsService merchantGroupGoodsService;
    @Resource
    private SkdLeaderInfoService skdLeaderInfoService;
    @Resource
    private SkdMemberInfoService skdMemberInfoService;
    @Resource
    private SkdGoodsSpecService skdGoodsSpecService;

    /**
     * #0005 获取订单列表
     * @param type    订单类型
     * @param keyword 搜索关键字
     * @return {@link UsGroupGoodsOrderRespVO} 返回订单列表
     */
    @ApiOperation("获取订单列表")
    @GetMapping
    public String getOrderList(@RequestParam(value = "type", required = false) Integer type,
                               @RequestParam(value = "keyword", required = false) String keyword) {
        Long usId;
        try {
            // 根据token获取用户id
            usId = tokenService.getUserIdFromToken();
        } catch (IllegalStateException e) {
            log.error(e.getMessage());
            return ReturnBody.error("token异常!");
        }

        // 检查type参数是否合法
        if (type != null && !Arrays.asList(0, 1, -2).contains(type)) {
            return ReturnBody.error("订单类型参数异常, 请传入正确参数!");
        }

        // 获取经过过滤的订单列表
        List<UsGroupGoodsOrder> usGroupGoodsOrderList = usGroupGoodsOrderService.getFilteredOrders(usId, type, keyword);

        // 批量获取相关信息，例如商家信息和团购商品信息
        // [代码逻辑：根据订单列表中的merchantId和groupGoodsId批量获取对应的商家和团购商品信息]

        // 转换订单列表到响应对象列表
        List<UsGroupGoodsOrderRespVO> usGroupGoodsOrderRespVOS = usGroupGoodsOrderList.stream()
                .map(order -> convertToRespVO(order))
                .collect(Collectors.toList());

        return ReturnBody.success(usGroupGoodsOrderRespVOS);
    }

    /**
     * 将订单对象转换为响应视图对象
     *
     * @param usGroupGoodsOrder 订单对象
     * @return 转换后的响应视图对象
     */
    private UsGroupGoodsOrderRespVO convertToRespVO(UsGroupGoodsOrder usGroupGoodsOrder) {
        UsGroupGoodsOrderRespVO respVO = new UsGroupGoodsOrderRespVO();

        // 设置基本的订单信息
        respVO.setOrderNo(usGroupGoodsOrder.getOrderNo());
        respVO.setCreateTime(usGroupGoodsOrder.getCreateTime());
        respVO.setRealPrice(usGroupGoodsOrder.getRealPrice());
        respVO.setCount(usGroupGoodsOrder.getCount());
        respVO.setRemark(usGroupGoodsOrder.getRemark());

        // 处理售后状态
        Integer afterSaleStatus = usGroupGoodsOrder.getAfterSaleStatus();
        if (afterSaleStatus != null && afterSaleStatus != 0) {
            if (afterSaleStatus == 1) {
                respVO.setStatus("申请退款中");
            } else if (afterSaleStatus == 2) {
                respVO.setStatus("退款完成");
            }
        } else {
            // 使用枚举获取订单状态描述
            GroupGoodsOrderStatusEnum statusEnum = GroupGoodsOrderStatusEnum.fromCode(usGroupGoodsOrder.getStatus());
            if (statusEnum != null) {
                respVO.setStatus(statusEnum.getDescription());
            } else {
                respVO.setStatus("未知状态");
            }
        }

        // 根据订单团购商品id查询团购商品主图url
        respVO.setGoodsMainImg(merchantGroupGoodsService.getGoodsMainImgById(usGroupGoodsOrder.getGroupGoodsId()));
        // 根据用用户id和拼团商品id查询团长id
        Long leaderId = skdMemberInfoService.getLeaderIdByUsIdAndGroupGoodsId(usGroupGoodsOrder.getUsId(), usGroupGoodsOrder.getGroupGoodsId());
        // 根据团长id查询跟团号并设置跟团号
        respVO.setGroupNo(skdLeaderInfoService.getGroupNoById(leaderId));
        // 获取并设置商家信息
        MerchantInfo merchantInfo = merchantInfoService.getById(usGroupGoodsOrder.getMerchantId());
        if (merchantInfo != null) {
            respVO.setMerchantName(merchantInfo.getStoreName());
            respVO.setMerchantAvatar(merchantInfo.getStoreAvatar());
        }

        // 获取并设置团购商品信息
        MerchantGroupGoods groupGoods = merchantGroupGoodsService.getById(usGroupGoodsOrder.getGroupGoodsId());
        if (groupGoods != null) {
            respVO.setGroupGoodsName(groupGoods.getTitle());
        }

        // 获取并设置商品规格信息
        SkdGoodsSpec spec = skdGoodsSpecService.getById(usGroupGoodsOrder.getSpecId());
        if (spec != null) {
            respVO.setSpecName(spec.getDescription());
            if (spec.getImgUrl() != null) {
                respVO.setSpecImgUrl(spec.getImgUrl());
            }
        }

        return respVO;
    }
}
